var app = getApp()
import ajaxhelper from '../../../utils/ajaxhelper.js';
import { signByMd5 } from "../../../utils/util";
var _this;
var model = require('../../../utils/ajaxhelper.js');
/**
 * @method
 * @desc 发表评论插件 
 * @author 
 * @param {string} id 同一页面可多处使用该插件，但不同的地方需传入不同的id名
 * @param {object} param 参数对象
 * @param {function} param.confirm 选择回调。会返回
 */
var set = function (id, param) {
  // 拿到当前页面对象
  var pages = getCurrentPages();
  _this = pages[pages.length - 1];
  //关闭音乐弹框
  _this.closeGloalVideo=function(e){
    // _this.data.isPlayGloalAudio = true;
    _this.setData({
      isPlayGloalAudio: false,
      isPlay: false,
      checkPlayList: false
    });
    app.backgroundAudioManager.pause();
    console.log(app.backgroundAudioManager)
  };
  _this.goAudioDetail=function(){
    wx.navigateTo({
      url: '../audioPlayDetail/audioPlayDetail',
    })
  };
  // 暂停 播放
  _this.controlAudio=function(){
    var that=_this;
    var isPlay = _this.data.isPlay;
    var urlObj = wx.getStorageSync('gloalObjUrl');
    console.log('2' + urlObj)
    urlObj = urlObj ? JSON.parse(urlObj) : {};
    if (!urlObj.url) {
      wx.showToast({
        title: '请购买视听',
        icon: 'loading'
      })
      return false;
    }
    /////
    if (that.data.curPlayIndex > that.data.resourcesList.length - 1) {
      // 获取下一首的地址
      // 判断是否为试听试看
      var curPlayIndex = that.data.resourcesList.length - 1;
      var resourcesItem = that.data.resourcesList[curPlayIndex];
      var url = (that.data.canView || (!that.data.canView && resourcesItem.snapshotFlag)) ? resourcesItem.url : '';///////////视频地址是试听地址还是正式地址
      // var url = that.data.canView ? resourcesItem.url : resourcesItem.snapshotUrl;///////////视频地址是试听地址还是正式地址
      var id = resourcesItem.id;//课程中资源id
      var courseId = resourcesItem.courseId;//课程id
      var index = curPlayIndex;//课程序号
      var cover = resourcesItem.cover;//资源封面
      var resourceItem = resourcesItem;//资源全部信息
      var lecturers = that.data.lecturers;//导师
      var obj = {
        url,
        id,
        courseId,
        index,
        cover,
        resourceItem,
        lecturers
      }
      // 存储要播放的urlobj
      wx.setStorage({
        key: 'gloalObjUrl',
        data: JSON.stringify(obj),
      })
      that.setData({
        curPlayIndex: curPlayIndex,
        playUrl: url,
        cover: cover || 'http://image.chuangchuang.cn/chuangchuang/cc_other/20171221/20171221_1513820857788.jpg',
      })
      // clearInterval(app.globalData.setIntervalId)
      that.play()//调用播放
      return false
    }
    ////
    if (isPlay){
      _this.setData({
        isPlay:false,
        checkPlayList:false
      })
      app.backgroundAudioManager.pause();
    }else{
      _this.setData({
        isPlay: true,
        checkPlayList: false
      })
      app.backgroundAudioManager.play();
    }   
  };
  //////////////////////
  // 播放下一首
  _this.playNextAudio=function(){
    var that = _this;
    if (that.data.curPlayIndex >= that.data.resourcesList.length - 1) {
      wx.showToast({
        title: '已经是最后一首喽',
        icon: 'loading'
      })
    } else {
      // 获取下一首的地址
      // 判断是否为试听试看
      var curPlayIndex = that.data.curPlayIndex + 1;
      var resourcesItem = that.data.resourcesList[curPlayIndex];
      // (canView || (!canView && resourceItem.snapshotFlag)) ? resourceItem.url : ''
      var url = (that.data.canView || (!that.data.canView && resourcesItem.snapshotFlag)) ? resourcesItem.url : '';///////////视频地址是试听地址还是正式地址
      var id = resourcesItem.id;//课程中资源id
      var courseId = resourcesItem.courseId;//课程id
      var index = curPlayIndex;//课程序号
      var cover = resourcesItem.cover;//资源封面
      var resourceItem = resourcesItem;//资源全部信息
      var lecturers = that.data.lecturers;//导师
      var obj = {
        url,
        id,
        courseId,
        index,
        cover,
        resourceItem,
        lecturers
      }

      // 存储要播放的urlobj
      wx.setStorage({
        key: 'gloalObjUrl',
        data: JSON.stringify(obj),
      })
      // urlObj: obj,
      //   currentPlayId: id,
      //     playUrl: url,
      //       curPlayIndex:index
      that.setData({
        curPlayIndex: curPlayIndex,
        playUrl: url,
        currentPlayId: id,
        // urlObj:obj,
        gloalObjUrl: obj,

      })
      that.play()//调用播放
      //播放统计
      app.addHit(id, 'RESOURCE_AUDIO');
    }
  }
  // 播放
  _this.play= function () {
    var that = _this, duration = that.data.duration, currentTime = that.data.currentTime;
    var currUrl = app.backgroundAudioManager.src;
    var backgroundAudioManager = app.backgroundAudioManager;
    // that.setData({
    //   isPlay: false
    // })
    if (!that.data.canView && !that.data.playUrl) {
      wx.showToast({
        title: '请购买视听',
        icon: 'loading'
      })
      return false;
    }
    if (!that.data.playUrl) {
      wx.showToast({
        title: '资源地址有误，请确认',
        icon: 'loading'
      })
      return false;
    }
    if ((currUrl && currUrl != that.data.playUrl) || !currUrl) {
      backgroundAudioManager.stop();
      backgroundAudioManager.src = that.data.playUrl;
      backgroundAudioManager.title = '结果大学'
      backgroundAudioManager.epname = '课程';
      backgroundAudioManager.singer = '结果大学';
      backgroundAudioManager.play();
      // backgroundAudioManager.title = '此时此刻'
      // backgroundAudioManager.epname = '此时此刻'
      // backgroundAudioManager.singer = '汪峰'
      that.setData({
        isPlay: true
      })

    } else if (currUrl && currUrl == that.data.playUrl) {
      if (that.data.isPlay) {
        that.controlAudio();
      } else {
        that.controlAudio()
      }

    }
    // backgroundAudioManager.onEnded(function () {
    //   that.setData({
    //     isPlay: false
    //   })
    //   ////
    //   if (that.data.curPlayIndex >= that.data.resourcesList.length - 1) {
    //     wx.showToast({
    //       title: '最后一首了',
    //       icon: 'loading'
    //     })
    //     that.setData({
    //       curPlayIndex: that.data.resourcesList.length
    //     })
    //     return false
    //   }
    //   /////
    //   // 获取全局音频信息 去缓存中取该资源是否付费
    //   var urlObj = wx.getStorageSync('gloalObjUrl');
    //   urlObj = urlObj ? JSON.parse(urlObj) : {};
    //   if (urlObj.canView) {
    //     that.setData({
    //       canView: true
    //     })
    //   }
    //   that.playNextAudio()
    // })
    // backgroundAudioManager.onError(function () {
    //   that.setData({
    //     isPlay: false
    //   })

    // })
    // backgroundAudioManager.onTimeUpdate(function () {
    //   duration = Math.ceil(backgroundAudioManager.duration);
    //   currentTime = Math.ceil(backgroundAudioManager.currentTime)
    //   var alePlayPrece = parseInt((currentTime / duration * 100)) || 0;
    //   that.setData({
    //     alePlayPrece
    //   })
    // })

  }
  _this.getAllDetail=function() {
    var that=_this;
    var id = that.data.urlObj.courseId;
    var token = (wx.getStorageSync('Token_date') && wx.getStorageSync('Token_date').Token) || '';
    ajaxhelper.get(app.globalData.frontJSHost + 'knowledge/detailById/' + id + '?token=' + encodeURIComponent(token), {}, that, that.setAllDetail)
  }
  _this.setAllDetail=function(res) {
    var that = this;
    if (res.result) {
      var indexList = res.data.indexList;
      if (indexList) {
        // 处理时间 数据
        var resourcesList = []; //吧所有课程放到一个数组里面
        indexList.forEach(function (item, index, arr) {
          if (item.resources && item.resources.length > 0) {
            item.resources.forEach(function (itemRe, index, arr) {
              itemRe.lengthObj = app.timeFormat(itemRe.length);
              itemRe.createDate = new Date(+itemRe.createDate).format("yyyy-MM-dd hh:mm");
              resourcesList.push(itemRe);
            })
          }
        })
        res.data.resourcesList = resourcesList;
      }
      if (res.data.updateDate) {
        res.data.updateDate = new Date(+res.data.updateDate).format("yyyy年MM月dd日");
      }
      if (res.data.statistics) {
        res.data.statistics.avgPoint = res.data.statistics.avgPoint && res.data.statistics.avgPoint.toFixed(1);///保留一位小数
      }
      that.setData({
        lecturers: res.data.lecturers,//讲师
        course: res.data.course,//视频简介介绍
        indexList: res.data.indexList,//视频列表
        // statistics: res.data.statistics,//评分评论
        // subject: res.data.subject,//分类
        canView: res.data.canView,//是否可以播放
        resourcesList: res.data.resourcesList,//处理好的资源列表
        // favoriteCount: res.data.favoriteCount,//订阅的个数
        // isSubscribe: res.data.favoriteStatus,//是否订阅
        // chapterCount: res.data.chapterCount,//总共集数
        // updateDate: res.data.updateDate,//更新日期
        // totalPrice: res.data.course.currentPrice,//购买价格
      })
      
    } else {
      wx.showToast({
        title: !!res.message.global ? res.message.global : "请求出错",
        icon: "loading"
      })
    }
    // that.play()//调用播放
  }
  
  /////////////////
}

var open = function (id) {
  _this.data.isPlayGloalAudio = true;
  _this.setData({
    isPlayGloalAudio:true,
    isPlay:true
  })
  // 获取全局音频信息
  var urlObj = wx.getStorageSync('gloalObjUrl');
  urlObj = urlObj ? JSON.parse(urlObj) : {};
  _this.setData({
    urlObj,
    gloalObjUrl: urlObj,
    playUrl: urlObj.url || '',
    currentPlayId: urlObj.id,
    curPlayIndex: urlObj.index,//正在播放的序号
  })
  _this.getAllDetail();//获取数据
}

/**
 * @func
 * @desc 设置data
 * @param {string} key 要设置的data的key值
 * @param {object} data 要设置的data
 */
function __SetData(key, data) {
  var pageData = {};
  pageData[key] = data;
  _this.setData(pageData);
  
}

module.exports = {
  set,
  open
}